package org.jeecg.modules.wechat;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.util.RedisUtil;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.wechat.service.WechatPaymentService;
import org.jeecg.modules.wechat.service.WechatSubscribeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;


@Slf4j
@Api(tags = "微信")
@RestController
@RequestMapping("/WeChat")
public class WeChatController {

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private RedisUtil redisUtil;

    @Value("${wechat.nurse.appid:}")
    private String appid;

    @Value("${wechat.nurse.appsecret:}")
    private String appsecret;



    @Autowired
    private WechatPaymentService wechatPaymentService;
    
    @Autowired
    private WechatSubscribeService wechatSubscribeService;

    @AutoLog(value = "微信获取用户openid")
    @ApiOperation(value = "微信获取用户openid", notes = "微信获取用户openid")
    @GetMapping(value = "/getOpenId")
    public Result<?> getOpenId(
            @RequestParam(value = "code") String code
    ) {

        HashMap<String, String> params = new HashMap<>();

        String url = "https://api.weixin.qq.com/sns/jscode2session?appid={appid}&secret={secret}&js_code={code}&grant_type={grant_type}";

        params.put("appid", appid);
        params.put("secret", appsecret);
        params.put("code", code);
        params.put("grant_type", "authorization_code");

        log.info("{}{}", appid, appsecret);

        String result = restTemplate.getForEntity(url, String.class, params).getBody();

        log.info("result{}", result);

        JSONObject jsonObject = JSON.parseObject(result);

        String openid = jsonObject.getString("openid");

        redisUtil.set(openid, openid, 5 * 60);

        return Result.OK(jsonObject);

    }

    @GetMapping("getPhoneNumber")
    @AutoLog(value = "微信-获取手机号")
    @ApiOperation(value = "微信-获取手机号", notes = "微信-获取手机号")
    @ResponseBody
    public Result<?> getPhoneNumber(
            @RequestParam(name = "phoneCode", required = false) String phoneCode,
            @RequestParam(name = "openIdCode") String openIdCode
    ) {

        JSONObject jsonObject;

        Map<String, String> params = new HashMap<>();

        String result;

        String access_token;

        String phoneNumber = null;

        String url;

        if (oConvertUtils.isNotEmpty(phoneCode)) {
            if (redisUtil.hasKey("wx_access_token")) {
                access_token = redisUtil.get("wx_access_token").toString();
            } else {
                url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={appid}&secret={secret}";

                params.put("appid", appid);

                params.put("secret", appsecret);

                result = restTemplate.getForEntity(url, String.class, params).getBody();

                jsonObject = JSON.parseObject(result);

                access_token = jsonObject.getString("access_token");

                redisUtil.set("wx_access_token", access_token, 7000);
            }
            params.clear();

            url = "https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=" + access_token;

            params.put("code", phoneCode);

            HttpHeaders headers = new HttpHeaders();

            headers.setContentType(MediaType.APPLICATION_JSON);

            HttpEntity<Map<String, String>> httpEntity = new HttpEntity<>(params, headers);

            ResponseEntity<JSONObject> response = restTemplate.postForEntity(url, httpEntity, JSONObject.class);


            if (oConvertUtils.isNotEmpty(response.getBody()) && oConvertUtils.isNotEmpty(response.getBody().getJSONObject("phone_info"))) {
                phoneNumber = response.getBody().getJSONObject("phone_info").getString("phoneNumber");
            }
        }

        url = "https://api.weixin.qq.com/sns/jscode2session?appid={appid}&secret={secret}&js_code={code}&grant_type={grant_type}";

        params.put("appid", appid);
        params.put("secret", appsecret);
        params.put("code", openIdCode);
        params.put("grant_type", "authorization_code");

        result = restTemplate.getForEntity(url, String.class, params).getBody();

        jsonObject = JSON.parseObject(result);

        String openid = jsonObject.getString("openid");

        redisUtil.set(openid, openid, 60);

        if (oConvertUtils.isNotEmpty(phoneNumber)) {
            redisUtil.set(openid + "_phone", phoneNumber, 60);
        }
        return Result.OK(jsonObject);
    }
    @GetMapping("sendMsg")
    @AutoLog(value = "微信-发送短信")
    @ApiOperation(value = "微信-发送短信", notes = "微信-发送短信")
    @ResponseBody
    public Result<?>  sendMsg(
            @RequestParam(name = "phoneNumberSet", required = true) String[] phoneNumberSet,
            HttpServletRequest req)
     {
         String sysOrg=req.getHeader("sys_org_code");
        return wechatPaymentService.sendVerifyCode(phoneNumberSet,sysOrg)?
        Result.ok(true):Result.error("发送验证码失败！",false);
    }

    @GetMapping("verifyCode")
    @AutoLog(value = "校验验证码")
    @ApiOperation(value = "微信-校验验证码", notes = "微信-校验验证码")
    @ResponseBody
    public Result<?>  verifyCode(HttpServletRequest request,
                                 @RequestParam(name = "phoneNumber", required = true) String phoneNumber,
                                 @RequestParam(name = "openId", required = true) String openId,
                                 @RequestParam(name = "inputCode") String inputCode
    ) {
       return wechatPaymentService.fnverifyCode(phoneNumber,inputCode,openId)?
                Result.ok(true):Result.error("校验验证码失败！",false);
    }


    @PostMapping("sendSubscribeMsg")
    @AutoLog(value = "微信-发送订阅号")
    @ApiOperation(value = "微信-发送订阅号", notes = "微信-发送订阅号")
    @ResponseBody
    public Result<?> sendSubscribeMsg(
            @RequestParam(name = "template", required = true) String template,
            @RequestParam(name = "page", required = true) String page,
             @RequestParam(name = "appid", required = true) String appid,
            @RequestParam(name = "appsecret", required = true) String appsecret,
            @RequestParam(name = "phone", required = true) String phone,
            @RequestParam(name = "openid", required = true) String openid
    ) {
        // 使用新创建的服务发送订阅消息
        try {
            // 这里我们直接调用新创建的服务方法
            Map<String, WechatSubscribeService.TemplateData> data = new HashMap<>();
            data.put("phone_number1", new WechatSubscribeService.TemplateData(phone));
            data.put("phrase2", new WechatSubscribeService.TemplateData("通过审核"));
            data.put("thing3", new WechatSubscribeService.TemplateData("已通过审核，请尽快签约腾讯电子签"));

            boolean success = wechatSubscribeService.sendSubscribeMessage(openid, template, data, page);
            
            if (success) {
                return Result.OK("订阅消息发送成功");
            } else {
                return Result.error("订阅消息发送失败");
            }
        } catch (Exception e) {
            log.error("发送订阅消息异常", e);
            return Result.error("发送订阅消息异常: " + e.getMessage());
        }
    }

    @GetMapping("over")
    @ResponseBody
    public Result<?>  test(HttpServletRequest request
    ) {
        System.out.println("回调成功！！");
        return Result.ok();
    }

}